<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Uindex extends Front_Controller {
	
	public $theme_data = array(
		'layout_main' => 'frontend/layout/home',
		'left' => 'frontend/include/left',
		'right' => 'frontend/include/right',

		);
	
	function __construct()
	{
		parent::__construct();
		$this->load->model('category_term_model','category_m');
		$this->load->model('event_term_model','event_m');
		$this->data['layout_id'] = 0;
	}
	public function index()
	{
		/*
		$this->load->module('Hello_world');
		$this->load->module('Hello_world');
		$this->load->module('Hello_world');
		
		echo 'Cach 1:';
		$this->Hello_world->run();
		echo '<br><br><br><br>';
		
		
		echo 'Cach 2:';
		echo Modules::run('Hello_world/xyz', 2,3,4,5);
		*/
		$this->load->model('post_m','post');
		
		
		$post = $this->post->get_many_by(array(
			'post_type' =>1,
			'comment_count' =>1,
			));
		print_r($post);
		$this->load->view('welcome_message');
		//$this->Post_m->delete(1);
		//prd(date('Y/m/d H:i:s',$post->post_time_start));
		//
	}
	
	function home()
	{
		$this->data['layout_id'] = 2;
		$this->theme_data['layout_main'] = 'frontend/layout/home';
		$this->template->view($this->theme_data, $this->data);
	}

	function category_parent($slug = '', $page = 1)
	{

	}

	function category_subcate($slug = '', $page = 1)
	{

	}
	
	function category($slug = '', $page = 1)
	{
		$this->load->model('layout_m');
		$page = 1;
		$layout_main = 'cateparent';
		$layout_id = 3;
		$arr_slug = $this->uri->segment_array();
		
		//$layout = $this->layout_m->parse_from_url();
		if(strpos(end($arr_slug), 'trang-') !== FALSE)
		{
			$page = array_pop($arr_slug);
			$page = str_replace('trang-','',$page);
			$page = (int)$page;
		}
		$slug = end($arr_slug);
		$cate = $this->category_m->get_by('term_slug', $slug);
		$this->data['nav_sub_menus'] = array();
		if($cate)
		{
			$this->data['catesubs'] = $this->category_m->get_menu($cate->term_id);
			$this->data['cate'] = $cate;
			$this->msystem->set_global('cate',$cate);

			//Nếu không có danh mục con thì nó là danh mục con
			if(empty($this->data['catesubs'])){
				$this->msystem->set_global('cat_id', $cate->term_id);
	            // set paging
				$this->msystem->set_global('cur_page', $page);
				$this->msystem->set_global('base_url', category_url($cate));

				$this->data['catesubs'] = $this->category_m->get_menu($cate->term_parent);
				$layout_main = 'catesub';
				$layout_id = 5;
			}
			else
			{
				
				$this->msystem->set_global('cat_id', $cate->term_id);
			}
		}
		else
		{
			show_404();
		}

		$this->data['layout_id'] = $layout_id;
		$this->theme_data['layout_main'] = 'frontend/layout/'.$layout_main;
		$this->template->view($this->theme_data, $this->data);
	}

	function event($slug = '', $page = 1)
	{
		
		$this->load->model('layout_m');
		$page = 1;
		$layout_main = 'cateparent';
		$layout_id = 6;
		$arr_slug = $this->uri->segment_array();
		
		//$layout = $this->layout_m->parse_from_url();
		if(strpos(end($arr_slug), 'trang-') !== FALSE)
		{
			$page = array_pop($arr_slug);
			$page = str_replace('trang-','',$page);
			$page = (int)$page;
		}
		$slug = end($arr_slug);
		$cate = $this->category_m->get_by('term_slug', $slug);
		$this->data['nav_sub_menus'] = array();
		if($cate)
		{
			$this->data['cate'] = $cate;
			$this->msystem->set_global('cate',$cate);
			$this->msystem->set_global('cat_id', $cate->term_id);
			$this->msystem->set_global('cur_page', $page);
			$this->msystem->set_global('base_url', term_url($cate));
		}
		else
		{
			show_404();
		}

		$this->data['layout_id'] = $layout_id;
		$this->theme_data['layout_main'] = 'frontend/layout/'.$layout_main;
		$this->template->view($this->theme_data, $this->data);
	}

	function search_keyword($search_terms = '')
	{
	    // If the form has been submitted, rewrite the URL so that the search
	    // terms can be passed as a parameter to the action. Note that there
	    // are some issues with certain characters here.
		if ($this->input->post('q'))
		{
			$str = $this->input->post('q');
			$str_convert = Replace_TiengViet($str);
			$string = preg_replace('/[^a-zA-Z0-9_%\[().\]\\/-]/s', '', $str_convert);
			$str_lower = mb_strtolower($string);
            // $string = addslashes( stripslashes( $str ) );
			redirect('/tim-kiem/' . $str_lower);

	    }// end if

	    //init var
	    $results = false;

	    if($search_terms){
	    	$this->load->model('post_m','post');
	    	$str_search = mb_strtolower($search_terms);

	         // paging
	    	$config = array();
	    	$this->data['posts'] = array();
	    	$p= $this->uri->segment(3, 0);
            $page = (int)substr(strrchr($p, "-"), 1); //substr($p, -1);
            $page = ($page <= 0) ? 1 : $page;
            
            $config['per_page']= 20; 
            $config['cur_page'] = $page;
            $config['base_url'] = base_url() . 'tim-kiem/' . $str_search;

            $params = array(
            	'posts_per_page'   => $config["per_page"],
            	);
            $str_search = str_replace("-", " ", $str_search);
            $config['total_rows'] = $this->post->like('post_slug',$str_search)->or_like('post_title', $str_search)->or_like('post_excerpt',$str_search)->num($params);

            $params['offset'] = ($config["cur_page"]-1)*$config["per_page"];
            $this->pagination->initialize($config);

	        // Perform the search
            $results = $this->post->like('post_slug',$str_search)->or_like('post_title', $str_search)->or_like('post_excerpt', $str_search)->get_posts($params);
	    }// end if

	    if($results)
	    {
	    	foreach($results as $i=>$post)
	    	{
	    		$this->data['posts'][$i] = $post;
	    		$this->data['posts'][$i]->url = post_url($post);
	    		$this->data['posts'][$i]->image = image($post->post_thumb,'post_thumb');
	    		$this->data['posts'][$i]->image_large = image($post->post_thumb,'post_thumb_large');
	    		$this->data['posts'][$i]->alias = str_replace('_', ' ', $post->post_slug);
	    	}
	    }

	    $this->msystem->set_global('breadscrum_title',$search_terms);

	    $this->data['layout_id'] = 2;
	    $this->theme_data['search_view'] = 'frontend/uindex/search';
	    $this->theme_data['layout_main'] = 'frontend/layout/home';
	    $this->template->view($this->theme_data, $this->data);

	}// end search_keyword()

	function page404()
	{
		$this->output->set_status_header('404');
		set_status_header(404);
		$this->data['noindex'] = TRUE;
		$this->theme_data["left"] = NULL;
		$this->theme_data["right"] = NULL;
		$this->theme_data["main"] = "frontend/include/page404";
		$this->template->view($this->theme_data, $this->data);
	}

	function view($slug){
		$this->load->model('post_m','mpost');
		$this->load->model('term_m','mterm');
		$this->load->model('comment_m','comment');
		// Get and check post_id by post_code
		@$post_id = explode("-", $slug);
		if ($post_id){
			$post_id = (int) end($post_id);
		} 

		// if ($post_id <= 0){
		// 	$query = '?q='.urlencode(substr(str_replace("-"," ",$slug),0,strlen ($query_str) - strlen(@$post_id)));
		// 	redirect(page404().$query, 301);
		// }

		// Get post
		$post = $this->mpost->get_post($post_id);

		// if (empty($post) || $post->pos_status < 1 || $post->pos_date_start > time()) {
		// 	$query = '?q='.urlencode(substr(str_replace("-"," ",$slug),0,strlen ($query_str) - strlen(@$post_id)));
		// 	redirect(page404().$query, 301);
		// }

		$this->data['post'] =  $post;
		$this->msystem->set_global('post', $post);

		$this->data['tags'] = $this->mterm->get_the_terms($post->post_id,'tag');
		$this->data['post_relate'] = array();
		$this->data['post_others'] = array();
		$cateids = array();
		$cates = $this->mterm->get_the_terms($post->post_id,'category');
		if($cates)
		{

			$this->msystem->set_global('cate', $cates[0]);
			$this->msystem->set_global('cat_id', $cates[0]->term_id);


			foreach ($cates as $c) $cateids[] = $c->term_id;

			if ($post->post_related != '') {
				$this->data['post_relate'] = $this->mpost->get_posts( array( 'include' => $post->post_related , 'exclude' => $post->post_id));
			}
			else
			{
				if($this->data['tags']){
					$tags_id = array();
					foreach ($this->data['tags'] as $tags) $tags_id[] = $tags->term_id;
					$this->data['post_relate'] = $this->mpost->get_posts( array( 'tag' => $tags_id , 'posts_per_page' => 6));
				}
				
				if(!$this->data['post_relate'] && $cateids)
					$this->data['post_relate'] = $this->mpost->get_posts( array( 'category' => $cateids , 'posts_per_page' => 6));
			}
		}

		if($cateids){
			$this->data['post_others'] = $this->mpost->get_posts( array( 'category' => $cateids , 'posts_per_page' => 6));
		}

		$this->data['comments'] = $this->comment->get_comments(array('comment_post_ID'=> $this->data['post']->post_id));
		
		$this->data['captcha'] = $this->captcha_setting();

		//seting post
		$this->data['post']->post_content = strip_tags($this->data['post']->post_content,'<br>,<img>,<a>,<b>,<i>,<u>,<table>,<p>,<em>,<strong>');
		$this->data['post']->post_show_type = $this->mpost->get_post_meta($this->data['post']->post_id,'_cms_post_show_type',true);
		$this->data['layout_id'] = 4;
		$this->theme_data['layout_main'] = 'frontend/layout/viewdetail';
		$this->theme_data['left_detail'] = 'frontend/uindex/left_detail';
		$this->template->view($this->theme_data, $this->data);
	}
	
	function test_cache()
	{
		$this->load->model('ads_m','ads');
		$r = $this->ads->set_cache()->get_many_by('ads_name','kaka');
		// $this->ads->delete_cache('hihicc2');
		prd($r);
	}

	function postcomment(){
		$this->load->model('comment_m', 'comment');
		$post = $this->input->post('edit');

		if($post){
			
			if(strtolower($_SESSION['captchaWord'])  != strtolower($this->input->post('captcha_word'))){
				echo "fail";
			}
			else{
				$post['comment_author_IP'] = $this->input->ip_address();
				$post['comment_date'] = time();

				$edit_id = $this->comment->insert($post);
				if($edit_id > 0){
					echo "1";
				}
				else{
					echo "0";
				}
			}
		}
	}

	function captcha_setting(){
		$this->load->helper('captcha');
		$values = array(
			'word' => '',
			'word_length' => 8,
			'img_path' => './images/captcha/',
			'img_url' => base_url() .'images/captcha/',
			'font_path' => base_url() . 'system/fonts/texb.ttf',
			'img_width' => '179',
			'img_height' => 40,
			'expiration' => 3600
			);
		$data = create_captcha($values);
		$_SESSION['captchaWord'] = $data['word'];
		return $data['image'];
	}

	function captcha_refresh(){
		$this->load->helper('captcha');
		$values = array(
			'word' => '',
			'word_length' => 8,
			'img_path' => './images/captcha/',
			'img_url' => base_url() .'images/captcha/',
			'font_path' => base_url() . 'system/fonts/texb.ttf',
			'img_width' => '179',
			'img_height' => 40,
			'expiration' => 3600
			);
		$data = create_captcha($values);
		$_SESSION['captchaWord'] = $data['word'];
		echo $data['image'];
	}

}
